<template>
  <div class="notice-manager">

    <el-row :gutter="10">
      <el-col :span="8">
        <el-card shadow="hover">
          <div class="list-header">
            <i class="el-icon-data-analysis" />
            <span>公告列表</span>
            <el-input v-model="keyword" size="mini" @blur="handlerBlur" />
            <div class="header-btn">
              <el-button size="mini" icon="el-icon-search" round @click="handlerFilter" />
            </div>
          </div>
          <el-table
            ref="table"
            v-loading="listLoading"
            :data="noticeList"
            style="width: 100%;"
            :header-cell-style="{'text-align':'center', background: '#4cbb86', color: '#fff'}"
            :cell-style="{'text-align':'center'}"
            size="small"
            empty-text="生气了...居然没有内容"
            class="tab-header"
            max-height="470"
            height="441"
            @expand-change="expandChange"
            @row-contextmenu="rightClick"
            @row-click="cancelMenu"
          >
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-form label-position="top" inline class="notice-table-expand">
                  <el-form-item label="创建时间">
                    <span>{{ props.row.createTime }}</span>
                  </el-form-item>
                  <el-form-item label="创建人区块">
                    <span>{{ props.row.createBy }}</span>
                  </el-form-item>
                  <el-form-item label="上次修改时间">
                    <span>{{ props.row.updateTime }}</span>
                  </el-form-item>
                  <el-form-item label="修改人区块">
                    <span>{{ props.row.updateBy }}</span>
                  </el-form-item>
                  <el-form-item label="公告等级">
                    <span>{{ props.row.grade }}</span>
                  </el-form-item>
                  <el-form-item label="公告内容">
                    <span v-html="props.row.content" />
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column
              prop="createTime"
              show-overflow-tooltip
            >
              <template slot="header">
                <i class="iconfont icon-shijian" />
                <span>创建时间</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="title"
              show-overflow-tooltip
            >
              <template slot="header">
                <i class="iconfont icon-biaoti" />
                <span>公告标题</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="pureText"
              show-overflow-tooltip
            >
              <template slot="header">
                <i class="iconfont icon-neirong" />
                <span>公告内容</span>
              </template>
            </el-table-column>
          </el-table>
          <!-- 右键菜单栏 -->
          <div
            v-show="menuVisible"
            id="contextmenu"
            class="menu"
          >
            <div
              class="contextmenu__item"
            >
              <el-button v-waves @click="hanlderEdit">修改</el-button></div>
            <div
              class="contextmenu__item"
            ><el-button v-waves @click="handlerDel">
              删除
            </el-button></div>
          </div>
          <Pagination
            v-show="total>0"
            layout="prev, slot, next"
            :page-sizes="[10]"
            :background="false"
            :total="total"
            :page.sync="listQuery.pageNo"
            :limit.sync="listQuery.pageSize"
            :small="true"
            @pagination="getList"
          />
        </el-card>

      </el-col>
      <el-col :span="8">
        <div class="chart-container">
          <div class="chart-header">
            <div class="left-title">
              <i class="iconfont icon-a-iconciyunpaopao" />
              <span>词云统计</span>
            </div>
            <div class="right-button">
              <el-button icon="el-icon-full-screen" round size="mini" @click="handlerFullScreen(1)" />
              <el-button icon="el-icon-refresh-right" round size="mini" @click="hanlderRefresh(1)" />
            </div>
          </div>
          <el-card id="word-cloud" shadow="hover">
            <!-- <div v-show="wordCloseBtn" class="close-btn">
              <el-button size="mini" icon="el-icon-close" circle @click="exitFullScreen(1)" />
            </div> -->
            <WordCloud id="word" :key="wordFlag" ref="wordCloud" :width="wordCloud.width" :height="wordCloud.height" :list-data="listData" />
          </el-card>
        </div>
        <div class="chart-container">
          <div class="chart-header">
            <div class="left-title">
              <i class="iconfont icon-zhishitupu1" />
              <span>知识图谱</span>
            </div>
            <div class="right-button">
              <el-button icon="el-icon-full-screen" round size="mini" @click="handlerFullScreen(2)" />
              <el-button icon="el-icon-refresh-right" round size="mini" @click="hanlderRefresh(2)" />
            </div>
          </div>
          <el-card id="know-graph" shadow="hover">
            <!-- <div v-show="wordCloseBtn" class="close-btn">
              <el-button size="mini" icon="el-icon-close" circle @click="exitFullScreen(1)" />
            </div> -->
            <Know id="know" :key="knowFlag" ref="knowGraph" :width="knowGraph.width" :height="knowGraph.height" />
          </el-card>
        </div>
      </el-col>

      <el-col :span="8">
        <div class="trace-info">
          <div class="info-header">
            <div class="left-desc">
              <i class="iconfont icon-guiji" />
              <span>公告轨迹</span>
            </div>
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              value-format="timestamp"
              size="mini"
              @change="filterDate"
            />
          </div>
          <div class="timedialog">
            <el-timeline>
              <el-timeline-item
                v-for="(item,index) in timeLineData"
                :key="index"
                placement="left"
                :color="color"
                :icon="item.icon"
              >
                <span>{{ item.key }}</span>
                <el-collapse v-model="activeName" accordion @change="handlerActiveIcon(index)">
                  <el-collapse-item class="first-order">
                    <el-card v-for="(it, ind) in item.children" :key="ind" shadow="hover">
                      <div slot="header" class="time-card-header">
                        <span style="fontWeight:700">{{ it.title }}</span>
                        <el-rate
                          :value="Number(it.grade)"
                          disabled
                          show-score
                          text-color="#ff9900"
                          score-template="{value}"
                        />
                        <el-button style="float: right;" size="mini" circle @click="it.isShow = !it.isShow;" />
                      </div>
                      <Transition name="timeline-card">
                        <el-descriptions v-show="it.isShow" class="margin-top" :column="1" direction="vertical">
                          <el-descriptions-item>
                            <template slot="label">
                              <i class="iconfont icon-chuangjianren" />
                              创建者区块 + 创建时间
                            </template>
                            <el-tag type="success">{{ it.createBy }}</el-tag>
                            - <el-tag>{{ it.createTime }}</el-tag>
                          </el-descriptions-item>
                          <el-descriptions-item>
                            <template slot="label">
                              <i class="iconfont icon-gengxinren" />
                              修改者区块 + 修改时间
                            </template>
                            <el-tag type="success">{{ it.updateBy }}</el-tag>
                            - <el-tag>{{ it.updateTime }}</el-tag>
                          </el-descriptions-item>
                          <el-descriptions-item label="纯文本内容" :span="2">
                            <template slot="label">
                              <i class="iconfont icon-icon" />
                              纯文本内容
                            </template>
                            {{ it.pureText }}
                          </el-descriptions-item>
                          <el-descriptions-item :span="2">
                            <template slot="label">
                              <i class="iconfont icon-Icon_fuwenbenkuang" />
                              富文本内容
                            </template>
                            {{ it.content }}
                          </el-descriptions-item>
                        </el-descriptions>
                      </Transition>
                    </el-card>
                  </el-collapse-item>
                </el-collapse>
              </el-timeline-item>
            </el-timeline>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 修改公告内容时的抽屉 -->
    <el-drawer
      title="修改公告"
      :visible.sync="drawer"
      :before-close="handlerClose"
      size="50%"
    >
      <el-descriptions :column="2" border style="padding:0 30px">
        <el-descriptions-item>
          <template slot="label">
            <i class="iconfont icon-biaoti" />
            修改公告标题
          </template>
          <el-input v-model="editContent.title" class="edit-input" />
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="iconfont icon-dengji" />
            等级
          </template>
          <el-rate
            v-model="editContent.grade"
            :colors="colors"
          />
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="iconfont icon-shijian" />
            最近修改时间
          </template>
          <el-tag size="small">{{ currentRow.updateTime }}</el-tag>
        </el-descriptions-item>
      </el-descriptions>
      <div class="editor-container">
        <Tinymce v-model="editContent.content" :width="580" :height="200" />
      </div>
      <div class="edit-footer">
        <el-button @click="drawer=false">取消</el-button>
        <el-button @click="submitEdit">提交</el-button>
      </div>
    </el-drawer>
  </div>

</template>

<script>
import waves from '@/directive/waves'
import { extract } from '@/utils/extract'
import { getNoticeList, delNoticeList, editNoticeList } from '@/api/notice'
import Pagination from '@/components/Pagination'
// 引入富文本编辑器
import Tinymce from '@/components/Tinymce'
// 引入 chart 组件
import WordCloud from '@/components/Charts/notice/WordCloud'
import Know from '@/components/Charts/notice//Know'
// 引入全屏插件
import screenfull from 'screenfull'
export default {
  name: 'Manager',
  directives: {
    waves
  },
  components: {
    Pagination,
    Tinymce,
    WordCloud,
    Know
  },
  data() {
    return {
      noticeList: [],
      tempList: [],
      listLoading: false,
      listQuery: {
        pageNo: 1,
        pageSize: 10,
        title: '',
        content: '',
        grade: ''
      },
      // 修改字段
      editContent: {
        title: '',
        content: '',
        grade: 0
      },
      // 总页数
      total: 0,
      // 搜索查询关键字
      keyword: '',
      // 右键菜单栏的模态框
      menuVisible: false,
      currentRow: {},
      // 控制抽屉的展开的关闭
      drawer: false,
      // rate 的变换颜色
      colors: ['#99A9BF', '#F7BA2A', '#FF9900'],
      // 修改字段
      // 监听 wordCloud 图表的宽度和高度信息
      wordCloud: {
        width: '0px',
        height: '0px'
      },
      // 监听 know 图表的宽度和高度信息
      knowGraph: {
        width: '0px',
        height: '0px'
      },
      // 控制组件重新渲染
      wordFlag: 0,
      knowFlag: 0,
      // 词云数据
      listData: [],
      // 控制词云关闭按钮的显示
      // wordCloseBtn: false,
      // 面板三：日期选择
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      dateRange: [],
      // timeline + collapse
      color: '#4fc08d',
      timeLineData: [],
      tempTimeLineData: [],
      activeName: ''
    }
  },
  created() {
    this.getList()
    // this.timeLineData()
  },
  mounted() {
    this.noticeList.forEach(v => {
      this.listData.push(v.pureText)
    })
    const wbDom = document.getElementById('word-cloud')
    const knowDom = document.getElementById('know-graph')
    // 将初次渲染的 DOM 的宽度和高度给chart容器
    this.wordCloud = { width: String(wbDom.clientWidth) + 'px', height: String(wbDom.clientHeight) + 'px' }
    this.knowGraph = { width: String(knowDom.clientWidth) + 'px', height: String(knowDom.clientHeight) + 'px' }
    // 重设视图更新标志
    const now = new Date().valueOf()
    this.wordFlag = now
    this.knowFlag = now
    // 开始监听事件
    const obWordCloud = new ResizeObserver(e => {
      const { width, height } = e[0].contentRect
      this.wordCloud = { width: String(width) + 'px', height: String(height) + 'px' }
      // console.log(this.wordCloud)
    })
    const obKnowGraph = new ResizeObserver(e => {
      const { width, height } = e[0].contentRect
      this.knowGraph = { width: String(width) + 'px', height: String(height) + 'px' }
    })
    obWordCloud.observe(wbDom)
    obKnowGraph.observe(knowDom)
  },
  beforeDestroy() {
    // ResizeObserver.unobserve()(document.getElementById('word-cloud'))
    // ResizeObserver.unobserve()(document.getElementById('know-graph'))
  },
  methods: {
    handlerActiveIcon(index) {
      if (this.timeLineData[index].icon === '') {
        this.timeLineData.forEach(v => { v.icon = '' })
        this.timeLineData[index].icon = 'el-icon-star-on'
      } else {
        this.timeLineData[index].icon = ''
      }
    },
    hanlderDate() {
      if (this.tempList && this.tempList.length === 0) return
      this.timeLineData = Array.from([])
      const arr = Array.from(this.tempList)
      arr.sort((a, b) => {
        return Date.parse(b.updateTime) - Date.parse(a.updateTime)
      })
      let key = arr[0].updateTime.split(' ')[0]
      this.timeLineData.push({ key, icon: '', children: [{ ...arr[0], isShow: false }] })
      for (let i = 1; i < arr.length; i++) {
        const t = arr[i].updateTime.split(' ')[0]
        if (t === key) {
          const len = this.timeLineData.length
          this.timeLineData[len - 1].children.push({ ...arr[i], isShow: false })
        } else {
          this.timeLineData.push({ key: t, icon: '', children: [{ ...arr[i], isShow: false }] })
          key = t
        }
      }
      this.tempTimeLineData = Array.from(this.timeLineData)
    },
    filterDate() {
      if (this.dateRange === null) {
        this.dateRange = []
        this.timeLineData = Array.from([])
        return
      }
      this.timeLineData = Array.from(this.tempTimeLineData.filter(v => {
        const t = new Date(v.key).getTime()
        return t >= this.dateRange[0] && t <= this.dateRange[1]
      }))
    },
    getList() {
      this.listLoading = true
      this.listData = []
      getNoticeList(this.listQuery).then(res => {
        this.noticeList = res.data.rows.map(v => {
          v.pureText = extract(v.content)
          this.listData.push(v.pureText)
          return v
        })
        // 再次更新word视图
        this.wordFlag = new Date().valueOf()
        setTimeout(() => {
          this.listLoading = false
        }, 500)
        this.tempList = Array.from(this.noticeList)
        this.total = Number(res.data.total)
        this.hanlderDate()
      })
    },
    // table 折叠面板手风琴
    expandChange(row, expandRows) {
      if (expandRows.length > 1) {
        expandRows.forEach((expandrow) => {
          if (row.id !== expandrow.id) {
            // toggleRowExpansion 设置是否展开，true则展开
            this.$refs.table.toggleRowExpansion(expandrow, false)
          }
        })
      }
    },
    handlerFilter() {
      this.noticeList = Array.from(this.tempList.filter(v => {
        return v.title.includes(this.keyword.trim())
      }))
    },
    handlerBlur() {
      if (this.keyword.trim() === '') {
        this.noticeList = Array.from(this.tempList)
      }
    },
    // 处理右键菜单栏
    rightClick(row, column, event) {
      this.currentRow = row
      // 禁止原生事件的发生
      event.preventDefault()
      this.testModeCode = row.testModeCode
      // 如果发现模态框已经打开则将其关闭，并打断事件的执行
      if (this.menuVisible) {
        this.menuVisible = false
        return
      }
      this.menuVisible = true // 显示模态窗口，跳出自定义菜单栏
      event.preventDefault() // 关闭浏览器右键默认事件
      this.CurrentRow = row
      var menu = document.querySelector('.menu')
      this.styleMenu(menu, event)
    },
    foo() {
      // 取消鼠标监听事件 菜单栏
      this.menuVisible = false
      document.removeEventListener('click', this.foo) // 关掉监听，
    },
    styleMenu(menu, event) {
      menu.style.left = event.pageX - 200 + 'px'
      menu.style.top = event.pageY - 110 + 'px'
    },
    cancelMenu() {
      this.menuVisible = false
    },
    async hanlderEdit() {
      if (JSON.stringify(this.currentRow) === '{}') return
      this.drawer = true
      this.menuVisible = false
      this.editContent.id = this.currentRow.id
      this.editContent.title = this.currentRow.title
      this.editContent.grade = Number(this.currentRow.grade)
      this.editContent.content = this.currentRow.content
      this.editContent.updateBy = this.currentRow.updateBy
      this.editContent.createBy = this.currentRow.createBy
    },
    async handlerDel() {
      this.menuVisible = false
      this.$confirm('请确认您正在删除公告?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async(action) => {
        if (action === 'confirm') {
          // this.drawer = false
          if (JSON.stringify(this.currentRow) !== '{}') {
            this.listLoading = true
            const res = await delNoticeList(this.currentRow.id)
            if (res.code === 200) {
              this.$notify({
                message: '删除公告成功',
                type: 'success'
              })
              setTimeout(() => {
                this.listLoading = false
              }, 500)
              this.getList()
            } else {
              this.$notify({
                message: '呜呜呜...出问题了',
                type: 'error'
              })
            }
          }
        }
      })
    },
    // 当点击提交修改的时的回调
    async submitEdit() {
      this.drawer = false
      const res = await editNoticeList(this.editContent)
      if (res && res.code === 200) {
        this.$notify({
          message: '公告修改成功',
          type: 'success'
        })
        this.getList()
      } else {
        this.$notify({
          message: '呜呜呜...出问题了',
          type: 'error'
        })
      }
      this.editContent = {}
    },
    // 抽屉的关闭处理事件
    handlerClose() {
      this.$confirm('修改的文本不会保留, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((action) => {
        if (action === 'confirm') {
          this.drawer = false
        }
      }).catch(() => {
      })
    },
    handlerFullScreen(order) {
      if (screenfull.enabled) {
        // this.wordCloud = window.screen.width
        // this.wordCloud = window.screen.height
        // this.wordFlag = new Date().valueOf()
        // this.hanlderRefresh(order)
        if (order === 1) {
          screenfull.request(document.getElementById('word-cloud'))
          // this.wordFlag = new Date().valueOf()
        }
        if (order === 2) {
          screenfull.request(document.getElementById('know-graph'))
          // this.knowGraph = new Date.valueOf()
        }
      }
    },
    hanlderRefresh(order) {
      if (order === 1) {
        this.$refs.wordCloud.initChart()
      }
      if (order === 2) {
        this.$refs.knowGraph.initChart()
      }
    },

    timeline(row) {
      this.$refs.timeline.open(true, row)
    },
    open(isEdit, obj) {
      this.innerVisible = true
    }
  }
}
</script>

<style lang="scss" scoped>
// 引入修改 button 的按钮样式
@import '@/styles/el-btn.scss';
@import '@/styles/scroll-bar.scss';
// 修改 v-loading 的颜色
::v-deep .el-loading-spinner .path{
  stroke: #4fc08d;
}
.notice-manager {
    padding: 10px 10px 0;
  .notice-table-expand {
    font-size: 0;
  }
  .notice-table-expand label {
    width: 90px;
    color: #99a9bf;
    span {
        font-size: 14px;
    }
  }
  .notice-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
    span {
        font-size: 12px;
    }
  }

  th[class^=el-table] {
    .iconfont {
        vertical-align:middle; font-size: 12px; padding-right: 4px
    }
  }

  .tab-header {
    border-radius: 10px 10px 0 0;
    // 表头内容过长时省略
    .header-ellipsis {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
  }
  }

  // 分页样式
//   .pagination-container {
//     padding: 0;
//   }
    @include my-scroll-bar;

    .el-card__body {
        .pagination-container {
            padding: 0;
            width: 100%;
            text-align: center;
            // 修改分页箭头
            ::v-deep .btn-prev {
                .el-icon-arrow-left::before {
                    content: "\e6ea"!important;
                }
            }
            ::v-deep .btn-next {
                .el-icon-arrow-right:before {
                    content: "\e6e9"!important;
                }
            }

        }
    }
    // 修改list的header部分
    .list-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 5px;
        i {
            width: 10px;
        }
        span {
            font-weight: bold;
            font-size: 10px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .el-input {
            width: 180px;
        }
    }
    @include my-el-button;
    @include my-el-input;
}

// 菜单拉样式单独设置

.menu {
  position: absolute;
  background-color: #fff;
  width: 100px;
  font-size: 12px;
  color: #444040;
  border-radius: 4px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  border-radius: 5px;
  border: 1px solid rgba(0, 0, 0, 0.15);
  box-shadow: rgba(0, 0, 0, 0.09) 0px 3px 12px;
  white-space: nowrap;
  z-index: 1000;
  overflow: hidden;
  .contextmenu__item {
    display: block;
    line-height: 34px;
    text-align: center;
    transition: all .7s;
    &:hover {
      background: #4fc08d;
      color: #fff;
    }
    .el-button {
      width: 100%;
      height:100%;
      margin:0;
      border-width: 0;
      border-radius: 0;
    }
  }
  .contextmenu__item:not(:last-child) {
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  }
}

.editor-container, .edit-footer {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
.edit-footer {
  justify-content: space-around;
}

// 设置词云容器
.chart-container {
  margin-bottom: 10px;
  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 5px;
    .left-title {
      i {
        vertical-align: middle;
        margin-right: 5px;
      }
      span {
        font-size: 10px;
        font-weight: 700;
      }
    }
  }

  // #word-cloud {
  //   position: relative;
  //   .close-btn {
  //     position: absolute;
  //     right: 5px;
  //     top: 5px;
  //     z-index: 999;
  //   }
  // }

  ::v-deep #word-cloud, ::v-deep #know-graph {
    height: 250px;
    .el-card__body {
      padding: 0;
    }
  }
}

// 轨迹面板样式
.trace-info {
  .info-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 5px;
    .left-desc {
      i {
        margin-right: 5px;
        width: 10px;
        vertical-align: middle;
      }
      span {
        font-size: 10px;
        font-weight: 700;
      }
    }
    // 设置激活时的边框样式
    // .el-range-editor.is-active:hover {
    //   border-color: #42b983;
    // }
    .el-date-editor {
      width: 230px;
    }
  }
}

.el-timeline {
  padding: 0;
}
// 时间线折叠面板设置
.el-timeline-item__content {
  .el-collapse {
    border: 0;
    .first-order {
      position: relative;
      // border: 1px solid red;
      z-index: 999;
      // background-color: transparent;
      opacity: 1;
      ::v-deep .el-collapse-item__header {
        height: 10px;
        margin-bottom: 25px;
        border: 0;
        background-color: transparent;
      }
      top: -14px;
      // height: 10px;
       ::v-deep .el-icon-arrow-right:before {
          color: #ccc!important;
          opacity: 1!important;
        }

        ::v-deep .el-collapse-item__wrap {
            border: 0;
        }

        ::v-deep .el-collapse-item__content {
          .el-card__header {
            padding: 7px 7px;
          }
          .el-card__body {
            padding: 7px;
          }
        }
      .el-card {
        margin-bottom: 10px;
      }
    }
  }
}

.time-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

// 卡片过渡效果
.timeline-card-enter, .timeline-card-leave-to {
  height: 0px;
}
.timeline-card-enter-to {
  height: 350px;
}

// .timeline-card-leave-from {
//   height: auto;
// }
.timeline-card-enter-active, .time-card-leave-active {
  transition: all 0.6s linear;
}
</style>
